<?php

namespace app\home\controller;

use app\common\controller\Home;

use PHPMailer\PHPMailer\PHPMailer;

use think\Request;

class User extends Home
{
	public function __construct(){
		parent::__construct();
		
		$this->UserModel = model('User.User');
		
		$this->RecordModel = model('User.Record');
		
		$this->PostModel = model('Post.Post');
		
		$this->CateModel = model('Post.Cate');
		
		$this->CommentModel = model('Post.Comment');
		
		$this->CollectModel = model('Post.Collect');
	}
    public function index()
    {
		$userid = $this->request->param('userid',0);
		
		// 查询自己发布的帖子
		$PostList = $this->PostModel->where('userid',$userid)->select();
		
		// 查询自己回复的帖子
		$CommentList = $this->CommentModel->with('post')->where('comment.userid',$userid)->paginate(4,false,['query' => Request::instance()->param()]);;
		
		// halt($CommentList);
		
		if($PostList === FALSE){
			$this->error('您还没有发布任何帖子');
		}
		
		if($userid)
		{
			$User = $this->UserModel->find($userid);

			if(!$User)
			{
				$this->error('该用户不存在',url('home/user/index'),null,0);
			}

			return $this->fetch('user',[
				'User' => $User,
				'PostList' => $PostList,
				'CommentList' => $CommentList
			]);
		}
			
        return $this->fetch();
    }
	// 基本资料
	public function profile()
	{
		$navTitle = '基本资料';

		if($this->request->isPost())
		{
			$action = $this->request->param('action','');

			if($action == 'profile')
			{
				$params = $this->request->param();

				// 封装数据
				$data = [
					'id' => $this->LoginUser['id'],
					'nickname' => $params['nickname'],
					'sex' => $params['sex'],
					'province' => $params['province'],
					'city' => $params['city'],
					'district' => $params['district'],
					'content' => $params['content']
				];

				// isUpdate == true ?  save = 更新数据  : 插入
				$result = $this->UserModel->isUpdate(true)->save($data);

				if($result === FALSE)
				{
					$this->error('更新基本资料失败',url('home/user/index'),null,0);
				}else{
					$this->success('更新基本资料成功',url('home/user/index'),null,0);
				}
			}
			
			// 更新头像
			if($action == 'avatar')
			{
				$avatar = upload('avatar');
			
				if($avatar['code'] === 0)
				{
					$this->error($avatar['msg']);
				}
			
				$data = [
					'id' => $this->LoginUser['id'],
					'avatar' => $avatar['data']
				];
			
				$result = $this->UserModel->isUpdate(true)->save($data);
			
				if($result === FALSE)
				{
					@is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
					$this->error('更新头像失败',url('home/user/index'),null,0);
				}else{
					@is_file('.' . $this->LoginUser['avatar']) && unlink('.' . $this->LoginUser['avatar']);
					$this->success('更新头像成功',url('home/user/index'),null,0);
				}
			}
			
			// 更新封面
			if($action == 'cover')
			{
				$cover = upload('cover');
			
				if($cover['code'] === 0)
				{
					$this->error($cover['msg']);
				}
			
				$data = [
					'id' => $this->LoginUser['id'],
					'cover' => $cover['data']
				];
			
				$result = $this->UserModel->isUpdate(true)->save($data);
			
				if($result === FALSE)
				{
					@is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
					$this->error('更新封面失败',url('home/user/index'),null,0);
				}else{
					@is_file('.' . $this->LoginUser['cover']) && unlink('.' . $this->LoginUser['cover']);
					$this->success('更新封面成功',url('home/user/index'),null,0);
				}
			}
		}
		// 查询地区的省份
		$provinces = model('Region')->where(['grade' => 1])->select();
		
		// 查询市
		if($this->LoginUser['province'])
		{
			$citys = model('Region')->where(['parentid' => $this->LoginUser['province']])->select();
		}else{
			$citys = [];
		}

		// 查询区
		if($this->LoginUser['city'])
		{
			$districts = model('Region')->where(['parentid' => $this->LoginUser['city']])->select();
		}else{
			$districts = [];
		}

		return $this->fetch('',[
			'navTitle' => $navTitle,
			'provinces' => $provinces,
			'citys' => $citys,
			'districts' => $districts
		]);
	}
	
	// 查询地区
	public function area()
	{
		if($this->request->isAjax())
		{
			$code = $this->request->param('code','');

			$list = model('Region')->where(['parentid' => $code])->select();

			if(!$list)
			{
				$this->error('选择地区不存在');
			}

			$this->success('查询成功',null,$list);
		}
	}
	
	// 修改密码
	public function setUppass(){
		
		if($this->request->isPost())
		{
			$action = $this->request->param('action','');
		
			if($action == 'pass')
			{
				// 
				$params = $this->request->param();
				// 生成新密码盐
				$salt = build_ranstr();
				// id
				$id = $this->LoginUser['id'];
				// 所有数据
				$list = $this->UserModel->where(['id' => $id])->select();
				// 旧用户密码
				$oldpassword = $list[0]['password'];
				// 旧密码盐
				$oldsalt = $this->LoginUser['salt'];
				
				// 用户输入的 旧密码
				$password = md5($params['password'].$oldsalt);
				
				// 新密码
				$newpassword = $params['newpassword'];
				
				// // 确认密码
				$pass = $params['repass'];
				
				// 
				if($password != $oldpassword){
					$this->error('旧密码输入错误',url('home/user/profile'),null,0);
				}
				
				if($newpassword != $pass){
					$this->error('确认密码不一致',url('home/user/profile'),null,0);
				}
				
				
				// 封装数据
				$data = [
					'id' => $this->LoginUser['id'],
					'password' => md5($newpassword.$salt),
					'salt' => $salt
				];
		
				// isUpdate == true ?  save = 更新数据  : 插入
				$result = $this->UserModel->isUpdate(true)->save($data);
		
				if($result === FALSE)
				{
					$this->error('修改密码失败');
				}else{
					cookie('LoginUser',null);
					$this->success('修改密码成功',url('home/user/index'),null,0);
				}
			}
		}
	}
	
	public function record()
	{
		$navTitle = '积分消费记录';
		
		// 消费状态
		$state = $this->request->param('state','');
		
		if(empty($state)){
			// 查询消费记录表
			$RecordList = $this->RecordModel->where(['userid' => $this->LoginUser['id']])->select();
		}else{
			// 查询消费记录表
			$RecordList = $this->RecordModel->where(['userid' => $this->LoginUser['id'],'state' => $state])->select();
		}
		
		return $this->fetch('',[
			'navTitle' => $navTitle,
			'RecordList'=> $RecordList,
			'state' => $state
		]);
	}
	
	// 查看收藏记录
	public function collect(){
		$navTitle = '收藏记录';
		
		// 接收分类id => 帖子 => 根据分类id去查询相应帖子
		$cateid = $this->request->param('cateid');
		
		$Userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;
		
		// 查询所有类型
		$CateList = $this->CateModel->select();
		
		// 条件数组
		$where = [];
		
		if(!empty($Userid))
		{
			$where['collect.userid'] = $Userid;
		}
		// 查询收藏的帖子
		// 查询是否收藏
		// $result = $this->CollectModel->where(['userid' => $userid , 'postid' => $postid])->find();->where($where)
		$CollectList = $this->CollectModel->with(['post'])->where($where)->select();
				
		return $this->fetch('',[
			'navTitle' => $navTitle,
			'CateList' => $CateList,
			'cateid' => $cateid,
			'CollectList' => $CollectList
		]);
	}
	
	// 我的帖子
	public function post()
	{
		$navTitle = '我的帖子';
		
		$Userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;
		
		// 查询自己发布的帖子
		$PostList = $this->PostModel->where('userid',$Userid)->select();
		
		if($PostList === FALSE){
			$this->error('您还没有发布任何帖子');
		}
		
		return $this->fetch('',[
			'PostList' => $PostList,
			'navTitle' => $navTitle
		]);
	}
	
	// 发送邮箱
	public function email(){
		if($this->request->isAjax()){
			$email = $this->request->param('email','');
			
			// 返回json格式
			// return json($email);
			
			$User = $this->UserModel->where(['email' => $email])->find();
			
			if(!$User){
				$this->error('该邮箱不存在');
			}
			
			$Email = md5($User['email'].$User['salt']);
			
			$content = "<a href='http://www.ask.com/home/index/auth?email=$Email'>点击认证</a>";
			 
			// 注册SMTP
			$mail = new PHPMailer(true);
			
			// 开启SMTP
			$mail->isSMTP(true);
			
			// SMTP服务器 qq => smtp.qq.com
			$mail->Host = "smtp.163.com";
			
			// 开启认证
			$mail->SMTPAuth = true;
			
			// 发送内容支持HTML
			$mail->IsHTML(true);
			
			// 账号
			$mail->Username = 'D1090300992@163.com';
			
			// 密码 => 不是邮箱密码，开启SMTP时的授权码
			$mail->Password = 'DTLNZYEANSWZYVWH';
			
			// 端口 服务器需要465端口
			$mail->Port = 465;
			
			// 协议
			$mail->SMTPSecure = 'ssl';
			
			// 发件邮箱
			$mail->From = 'D1090300992@163.com';
			
			// 发件人名字
			$mail->FromName = "ASK论坛";
			
			// 接收回复的邮箱
			$mail->addReplyTo('D1090300992@163.com',"ASK论坛");
			
			// 收件人
			$mail->addAddress($User['email'],$User['nickname']);
			
			// 邮箱主题
			$mail->Subject = '账号认证';
			
			//设置多少个字符换行 80字符
			$mail->WordWrap = 80;
			
			// 发送HTML内容
			$mail->msgHTML($content);
			
			$result = $mail->send();
			
			if($result === FALSE)
			{
				$this->error('发送邮件失败');
			}else {
				$this->success('发送邮件成功');
			}
			
		}
	}
}